/*
 * Copyright (c) 2024. hallele, Inc All rights reserved.
 */

package cn.hallele.ms.infrastructure.core.aspect.controller;

import cn.hallele.infrastructure.metadata.constant.MsgCodeConst;
import cn.hallele.infrastructure.metadata.io.Metric;
import cn.hallele.infrastructure.metadata.io.Response;
import cn.hallele.infrastructure.util.DateUtil;
import cn.hallele.infrastructure.util.NetUtil;
import cn.hallele.infrastructure.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.Locale;

/**
 * hallele_mc_core
 *
 * @author anle5
 * @since 2024/9/15 0:28
 */
@Slf4j
public class BaseExceptionAspect {
    /**
     * 国际化
     */
    protected final MessageSource i18n;

    /**
     * 国际化
     *
     * @param i18n i18n
     */
    public BaseExceptionAspect(MessageSource i18n) {
        this.i18n = i18n;
    }

    /**
     * 构建响应
     *
     * @param msgCode 响应码
     * @param msgDesc 响应描述
     * @return 响应
     */
    protected Response<Object> buildResponse(String msgCode, String msgDesc) {
        return Response.builder()
                .metric(Metric.builder()
                        .success(ObjectUtil.equals(MsgCodeConst.SUCCESS, msgCode))
                        .msgCode(msgCode)
                        .msgDesc(msgDesc)
                        .requestId(NetUtil.getRequestId())
                        .completedTime(DateUtil.nowDate())
                        .build())
                .build();
    }

    /**
     * 获取异常信息
     *
     * @param e 异常
     * @return 异常信息
     */
    protected String getErrorMsg(Throwable e) {
        return StringUtils.isBlank(e.getMessage()) ? e.getCause().getMessage() : e.getMessage();
    }

    /**
     * 获取语言
     *
     * @return Locale
     */
    protected Locale getLocale() {
        return LocaleContextHolder.getLocale();
    }
}
